package com.diaohw.platform.framework.authorization;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import com.diaohw.platform.common.obj.login.LoginUser;
import com.diaohw.platform.common.obj.thread.LoginThread;
import com.diaohw.platform.common.properties.AuthorizationProperties;
import com.diaohw.platform.common.properties.GlobalProperties;
import jakarta.annotation.Resource;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Order(1)
@Component
public class AuthorizationWebInterceptors implements WebMvcConfigurer {

    @Resource
    private AuthorizationProperties config;
    @Resource
    private GlobalProperties globalProperties;
    @Resource
    private OnlineManager onlineManager;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {


        // 自定义拦截器，logger MDC 请求信息初始化
        registry.addInterceptor(new SaInterceptor(handle -> {

                            if (StpUtil.isLogin()) {
                                // 设置用户名
                                LoginUser user = AuthorizationUtil.getLoginUser();
                                if (config.isOnline()) {
                                    onlineManager.refresh(user.getLoginId());
                                }
                                LoginThread.init(user);
                            }
                            // 校验登录
                            if (globalProperties.isCheckLogin()) {
                                StpUtil.checkLogin();
                            }

                        })

                )
                .addPathPatterns(config.getPathPatterns())
                .excludePathPatterns(config.getExcludePathPatterns());
    }
}
